<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="setSetting">今日秒杀时间配置</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <!-- 列表 -->
    <el-table :data="list">
       <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="英文名称" align="center" prop="englishName" />
      <el-table-column label="图片" align="center" prop="img">
        <template v-slot="scope">
          <div class="imgboxlun" v-if="scope.row.url">
            <img class="imgstylelun" :src="scope.row.url" alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button v-show=" scope.row.id != 4" size="mini" type="text" icon="el-icon-edit"  @click="productMent(scope.row)">推荐产品管理</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,2)">导航栏图片</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="90%" v-dialogDrag append-to-body>
      <div class="dialog-box">
        <el-form class="box-item queryform" ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="英文名称" prop="name">
            <el-input v-model="form.englishName" placeholder="请输入英文名称" />
          </el-form-item>
          <el-form-item label="图片">
            <!-- <editor v-model="form.content" :min-height="192"/> -->
             <el-upload
                  class="upload-demo"
                  ref="upload"
                  :action="actives"
                  :headers="headers"
                  :http-request="uploadSectionFileimgInfo"
                  :on-remove="handleRemoveimgInfo"
                  :file-list="filelistimgInfo"
                  :limit="1"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
                </el-upload>
          </el-form-item>
        </el-form>
<!--        &lt;!&ndash; 商品列表 &ndash;&gt;-->
<!--        <el-table :data="Goodslist">-->
<!--        <el-table-column label="选中" align="center" prop="type" >-->
<!--            <template v-slot="scope">-->
<!--              <el-checkbox @change="(e)=>changeCheck(e,scope.row)" v-model="scope.row.check"></el-checkbox>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="id" align="center" prop="id" />-->
<!--          <el-table-column label="商品名称" align="center" prop="name" />-->
<!--          <el-table-column label="图片" align="center" prop="img">-->
<!--            <template v-slot="scope">-->
<!--              <div class="imgbox" v-if="scope.row.img.length !== 0">-->
<!--                <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">-->
<!--                <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i class="el-icon-arrow-left"></i></div>-->
<!--                <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)" ><i class="el-icon-arrow-right"></i></div>-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="商品分类" align="center" prop="type" >-->
<!--            <template v-slot="scope">-->
<!--              <span>{{gettype(scope.row.type)}}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="销售数量" align="center" prop="saleNum" />-->
<!--          <el-table-column label="商品上架状态" align="center" prop="status">-->
<!--            <template v-slot="scope">-->
<!--              <el-tag :type="scope.row.status == 1 ? 'success' : 'info'" effect="dark">{{statusobj[scope.row.status]}}</el-tag>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->

        <pagination v-show="Goodslisttotal > 0" :total="Goodslisttotal" :page.sync="goodsQueryParams.pageNo" :limit.sync="goodsQueryParams.pageSize"
                @pagination="getGoodsList"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 推荐产品管理 -->
    <el-dialog :title="title" :visible.sync="productMentShow" width="90%" v-dialogDrag append-to-body>
      <div class="dialog-box">
        <el-input style="width:300px;margin:20px" v-model="goodsQueryParams.name" placeholder="请输入商品名称,回车查询" clearable @keyup.enter.native="getGoodsListPage"/>
        <el-input style="width:300px;margin:20px" v-model="goodsQueryParams.code" placeholder="请输入商品名称,回车查询" clearable @keyup.enter.native="getGoodsListPage"/>
        <!-- 商品列表 -->
        <el-table :data="Goodslist">
        <el-table-column label="选中" align="center" prop="type" >
            <template v-slot="scope">
              <el-checkbox @change="(e)=>changeCheck(e,scope.row)" v-model="scope.row.check"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="商品编号" align="center" prop="code" />
          <el-table-column label="商品名称" align="center" prop="name" />
          <el-table-column label="图片" align="center" prop="img">
            <template v-slot="scope">
              <div class="imgbox" v-if="scope.row.img.length !== 0">
                <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">
                <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i class="el-icon-arrow-left"></i></div>
                <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)" ><i class="el-icon-arrow-right"></i></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品分类" align="center" prop="type" >
            <template v-slot="scope">
              <span>{{gettype(scope.row.type)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售数量" align="center" prop="saleNum" />
          <el-table-column label="商品上架状态" align="center" prop="status">
            <template v-slot="scope">
              <el-tag :type="scope.row.status == 1 ? 'success' : 'info'" effect="dark">{{statusobj[scope.row.status]}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="Goodslisttotal > 0" :total="Goodslisttotal" :page.sync="goodsQueryParams.pageNo" :limit.sync="goodsQueryParams.pageSize"
                @pagination="getGoodsList"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="productMentSubmitForm">确 定</el-button>
        <el-button @click="productMentShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 今日秒杀时间配置 -->
    <el-dialog title="今日秒杀时间配置" :visible.sync="miaoTimeSetShow" width="300px" v-dialogDrag append-to-body>
      <el-date-picker
        v-model="miaoTimeSetVaule"
        type="datetime"
        value-format="timestamp"
        placeholder="选择日期时间">
      </el-date-picker>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setSettingConfig">确 定</el-button>
        <el-button @click="miaoTimeSetShow = false">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导航栏图片 -->
    <el-dialog
      title="导航栏图片"
      :visible.sync="piliangEditshow"
      width="800px">
      <div  class="piliang">
        <h2>{{form.name}}</h2>
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="actives"
          :headers="headers"
          :http-request="bannaFileimgInfo"
          :on-remove="handleRemoveimgInfo"
          :file-list="bannaFiles"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
        </el-upload>
      </div>
      <span  slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pichangeimgSortConfirm">确 定</el-button>
        <el-button @click="piliangEditshow = false">取 消</el-button>

      </span>
    </el-dialog>
  </div>


</template>

<script>
import { createGoods, updateGoods, deleteGoods, getGoods, getGoodsPage, exportGoodsExcel } from "@/api/qd/goods";
import Editor from '@/components/Editor';

export default {
  name: "Goods",
  components: {
    Editor
  },
  data() {
    return {
      actives: process.env.VUE_APP_BASE_API+'/pc/file/upload',
      headers:{Authorization: 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')} ,
      specifobj:{},
      childobj:{},
      filelist:[],
      waifilelist:[], // 最外层的图片数组
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序-商品列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      baoyouobj:{1:'是',2:'否'},
      statusobj:{1:'上架',2:'下架'},
      options:[], // 商品分类详情数据
      openspcifshow:false,
      isedit:null,
      postalIdoptions:[], // 运费模板数据
      filelistimgInfo:[], // 图文详情
      bannaFiles:[], // 导航栏图片集合
      Goodslisttotal:0,
      goodsQueryParams:{
        pageNo: 1,
        pageSize: 10,
      },
      Goodslist:[],
      // 今日秒杀时间配置
      miaoTimeSetShow:false,
      miaoTimeSetVaule:null,

      piliangEditshow:false, // 导航栏图片
      changeTableList:[], // 选中的表格列表
      // 推荐产品管理
      productMentShow:false
    };
  },
  created() {
    this.getList();
    // 获取其他数据
    this.fenleiList()
    this.getGoodsList()
  },
  methods: {
    productMent(row){//推荐产品管理
      this.goodsQueryParams.pageNo = 1
      this.getGoodsList()
      this.reset();
      this.waifilelist=[]
      const id = row.id;
      this.$axios({url:'/qd/amway/getById',method:'get',params:{id}}).then(response => {
        this.form = response.data;
        this.filelistimgInfo=[]
        if(this.form.url) this.filelistimgInfo=[{url:this.form.url}]
        this.Goodslist.forEach(item=>{
          this.$set(item,'check',false)
        })
        this.checkorderList()
        this.productMentShow = true;
        this.title = "推荐产品管理";
      });
    },
    productMentSubmitForm(){//推荐产品管理确认按钮
      let obj = JSON.parse(JSON.stringify(this.form))
      this.$axios({url:'/qd/amway/update',method:'put',data:obj}).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.productMentShow = false;
        this.getList();
        this.goodsQueryParams.name=''
        this.goodsQueryParams.code=''
        this.getGoodsList();
      });
    },
    pichangeimgSortConfirm(){ // 批量修改图片弹窗确认按钮
      if(this.bannaFiles.length === 0) return this.$message.warning('最少上传一张')
      this.form.imgs = []
      this.bannaFiles.forEach(item=>{
        this.form.imgs.push(item.url)
      })
      this.$axios({url:'/qd/amway/update',method:'put',data:this.form}).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.piliangEditshow = false;
        this.getList();
        this.bannaFiles=[];
      });
    },

    fenleiList(){
      // 获取商品分类数据
      this.$axios({url:'qd/goodsType/getTree',method:'get'}).then(res=>{
        this.options = res.data ?? []
        // 删除第三层级的children
        this.options.forEach(item=>{
          item.children.forEach(ite=>{
            ite.children.forEach(it=>{
              delete it.children
            })
          })
        })
      })
    },
    setSetting(){ // 今日秒杀时间配置
      this.$axios({url:'/qd/amway/getTime',method:'get'}).then(res=>{
        this.miaoTimeSetVaule = res.data ?? null
        this.miaoTimeSetShow = true
      })
    },
    setSettingConfig(){ // 今日秒杀时间配置 弹窗确认
      this.$axios({url:'/qd/amway/setTime',method:'get',params:{time:this.miaoTimeSetVaule}}).then(res=>{
        this.$message.success('配置成功')
        this.miaoTimeSetShow = false
        this.getList()
      })
    },
    changeCheck(val,row){
      // 选中复选框时触发
      if(this.form.infos instanceof Array){}else{
        this.form.infos = []
      }
      // 如果为真就往里添加，如果是false就自动删除
      if(val){
          this.form.infos.push({...row,goodId:row.id})
        }else{
          this.form.infos.forEach((item,index)=>{
            if(item.goodId === row.id) return this.form.infos.splice(index,1)
          })
        }
    },
     checkorderList(){
      // 判断是否有选中的商品
      if(this.form.infos instanceof Array){
        this.Goodslist.forEach(item=>{
          let arr = this.form.infos.filter(ite=>item.id === ite.goodId)
          if(arr.length !== 0) this.$set(item,'check',true)
        })
      }

    },
    toleft(index,imglength,iindex){  // 图片向右
        if(iindex === 0) return this.Goodslist[index].imgIndex = imglength - 1 ?? 0
        this.Goodslist[index].imgIndex -= 1
    },
    toright(index,imglength,iindex){  // 图片向左
        if(imglength - 1 === iindex) return this.Goodslist[index].imgIndex = 0
        this.Goodslist[index].imgIndex += 1
    },
    uploadSectionFileimgInfo(val){
      let file = val.file
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {

            this.filelistimgInfo.push({url:res.data})
            this.form.url = res.data
            this.$message.success('上传成功')
        })
    },
    //导航栏上传图片
    bannaFileimgInfo(val){
      let file = val.file
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {

        this.bannaFiles.push({url:res.data})
        // this.form.imgs.push(res.data)
        this.$message.success('上传成功')
      })
    },

    handleRemoveimgInfo(file, fileList){ // 移除图片时
      this.filelistimgInfo = fileList
      this.bannaFiles=fileList
    },
    gettype(str){  //根据商品类型id获取值
      let a = '',b='',c=''
      if(str){
        let arr = str.split(',')
        this.options.forEach(item=>{
          if(item.value === Number(arr[0])){
            a=item.label ?? ''
            item.children.forEach(ite=>{
              if(ite.value === Number(arr[1])){
                b=item.label ?? ''
                ite.children.forEach(it=>{
                  if(it.value === Number(arr[2])){
                    c = it.label ?? ''
                  }
                })
              }
            })
          }
        })
      }
      return a + b +c
    },

    /** 查询列表 */
    getList() {
       this.loading = true;
      // 执行查询
      this.$axios({url:'/qd/amway/page',method:'get',params:this.queryParams}).then(res=>{
        this.list = res.data ?? []
      })
    },
    getGoodsListPage(){
      this.goodsQueryParams.pageNo = 1
      this.getGoodsList()
    },
    getGoodsList(){
    //  获取商品数据
      getGoodsPage(this.goodsQueryParams).then(response => {
        this.Goodslist = response.data.list ?? [];
        this.Goodslist.forEach(item=>{
          this.$set(item,'imgIndex',0)
          this.$set(item,'check',false)
        })
        this.checkorderList()
        this.Goodslisttotal = response.data.total;
        this.loading = false;
      });
    },

    /** 取消按钮 */
    cancel() {
      console.log(222)
      this.open = false;
      this.reset();
    },
    bannaCancel() {
      console.log(111)
      this.piliangEditshow = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.filelist=[]
      this.waifilelist = []
      // this.$refs.upload.forEach((item,index)=>{
      //   this.$refs.upload[index].clearFiles();
      // })
      this.open = true;
      this.title = "添加小程序-好物精选";
    },
    /** 修改按钮操作 */
    handleUpdate(row,num) {
      this.reset();
      this.waifilelist=[]
      const id = row.id;
      this.$axios({url:'/qd/amway/getById',method:'get',params:{id}}).then(response => {
        this.form = response.data;
        this.filelistimgInfo=[]
        // 导航栏图片
        if(num === 2){
          this.bannaFiles = []
          if(this.form.imgs instanceof Array){
            this.form.imgs.forEach(item=>{
              this.bannaFiles.push({url:item})
            })

          }
          this.piliangEditshow = true
          return
        }
        if(this.form.url) this.filelistimgInfo=[{url:this.form.url}]
        this.Goodslist.forEach(item=>{
          this.$set(item,'check',false)
        })
        this.checkorderList()
        this.open = true;
        this.title = "修改小程序-好物精选";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        let obj = JSON.parse(JSON.stringify(this.form))
        // obj.list = {...obj.infos}
        // delete obj.infos
        // 修改的提交
        if (this.form.id != null) {
          this.$axios({url:'/qd/amway/update',method:'put',data:obj}).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        this.$axios({url:'/qd/amway/addList',method:'post',data:obj}).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除?').then(function() {
          return this.$axios({url:'/qd/amway/deleteById?id='+id,method:'delete'});;
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有小程序-商品数据项?').then(() => {
          this.exportLoading = true;
          return exportGoodsExcel(params);
        }).then(response => {
          this.$download.excel(response, '小程序-商品.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/minImgStyle.scss";
.dialog-box{
  // display:flex;
  // .box-item{
  //   width: 50%;
  // }
  // .queryform{
  //   display: flex;
  //   flex-wrap: wrap;
  //   .el-form-item{
  //     width: 45%;
  //     text-align: center;
  //   }
  // }
}
.imgstylelun{
  width:150px;
  height: 100px;
}
.piliang{
  margin-top:20px;
}
</style>
